package com.king.juc.threads;

import lombok.extern.slf4j.Slf4j;

/**
 * 两阶段终止模式
 * @author king
 * @date 2020/9/27 13:29
 */
@Slf4j(topic = "c.TwoStageTermination")
public class TwoStageTermination {
    private Thread monitor;

    /**
     * 启动监控线程
     */
    public void start(){
        monitor = new Thread(() -> {
            while(true){
                Thread current = Thread.currentThread();
                if (current.isInterrupted()){
                    log.debug("后续收尾逻辑.....");
                    break;
                }

                try {
                    // 情况1
                    Thread.sleep(1000);
                    // 情况2
                    log.debug("执行监控记录.....");
                } catch (InterruptedException e) {
                    // sleep出现异常后, 会清除打断标记
                    e.printStackTrace();
                    // 设置打断标记
                    current.interrupt();
                }
            }
        });

        monitor.start();
    }

    /**
     * 停止监控线程
     */
    public void stop(){
        monitor.interrupt();
    }

    public static void main(String[] args) throws InterruptedException {
        TwoStageTermination tpt = new TwoStageTermination();
        tpt.start();

        Thread.sleep(3500);

        tpt.stop();
    }
}
